import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)



const store = new Vuex.Store({
	state: () => ({
		storeList: uni.getStorageSync('storeList') || [],
		activeStoreId: uni.getStorageSync('active_id') || -1,
		userInfo: uni.getStorageSync('userinfo') || {},
	}),
	getters: {
		payload(state, getters) {
			if (!getters.token.length) return -1
			const { mobile } = state.userInfo
			const { activeStore } = getters
			if (activeStore.id === -1) return -2
			console.log(getters, 'getters');
			return {
				mobile,
				store_id: activeStore.id
			}
		},
		userInfo(state) {
			return state.userInfo
		},
		token(state) {
			let token = ''
			const { userInfo } = state
			if (userInfo.hasOwnProperty('token')) {
				token = userInfo.token
			}
			return token
		},
		activeStore(state) {
			const { storeList, activeStoreId } = state
			if (!storeList.length) return { id: -1, name: '未选择' }
			if (activeStoreId === -1) return { id: -1, name: '未选择' }
			const target = storeList.find(item => item.id === activeStoreId)
			console.log(target, 'activeStore');
			if (!!target) return target
			return { id: -1, name: '未选择' }
		},
	},
	actions: {

	},
	mutations: {
		logout(state) {
			state.storeList = []
			state.activeStoreId = -1
			state.userInfo = {}
			uni.clearStorage();
		},
		setUserInfo(state, value) {
			state.userInfo = value
			uni.setStorageSync('userinfo', value)
			const { token } = value
			uni.setStorageSync('token', token)
		},
		setActiveId(state, id) {
			if (state.activeStoreId === id) return
			state.activeStoreId = id
			uni.setStorageSync('active_id', id)
		},
		setStoreList(state, { value, init }) {
			if (!Array.isArray(value) || !value.length) return
			console.log(value, 'storeList');
			state.storeList.splice(0, state.storeList.length, ...value)
			uni.setStorageSync('storeList', value)
			if (init) {
				const [targetStore] = value
				const { id } = targetStore
				state.activeStoreId = id
				uni.setStorageSync('active_id', id)
			}
		},
	},
})

export default store